/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package generator;

import generator.connection.ConnectionDialog;
import generator.connection.DataBaseConnectionModel;
import generator.connection.SQLConnectionDatabase;
import generator.relationships.DataBaseRelationshipsModel;
import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import jsf.generator.CommonJSFControllerGenerator;
import jsf.generator.CommonJSFPagesGenerator;
import jsf.generator.GeneratePropertiesFile;
import jsf.generator.JSFPaginationClassWriter;
import jsf.generator.controller.JSFBaseControllerClassWriter;
import jsf.generator.controller.JSFUtilWriter;
import net.db.generator.BaseListModel;
import net.db.generator.JavaBaseClassWriter;
import net.db.generator.JavaBaseInterfaceWriter;
import net.db.generator.JavaBasePKClassWriter;
import net.db.generator.JavaConnectionClassWriter;
import net.db.generator.JavaConnectionPropertiesWriter;
import net.db.generator.JavaDAOBaseClassWriter;
import net.db.generator.JavaDAOBaseInterfaceWriter;
import net.db.generator.JavaDAOClassWriter;
import net.db.generator.JavaDAOFullClassWriter;
import net.db.generator.field.models.BaseFieldModel;
import net.db.generator.field.models.DataBaseColumnType;
import net.db.generator.field.models.SQLTypeMap;
import net.db.generator.utils.ClassGeneratorUtil;
import net.etfbl.jgroky.jdbc.DBConnection;

/**
 *
 * @author abosancic
 */
public class ClassGenerator extends javax.swing.JFrame {

    /**
     * Creates new form ClassGenerator
     */
    public ClassGenerator() {
        initComponents();
        generateBtn.setEnabled((dbGenList.getSelectedValue() != null));
        try {
            db = new SQLConnectionDatabase();
            dbUtils = new DatabaseUtils();
            //checkDataBaseConnection();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ClassGenerator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ClassGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
        createAndShowGUI();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        generateBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        dbList = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        dbTablesList = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        dbColumnsList = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        dbGenList = new javax.swing.JList();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldDTO = new javax.swing.JTextField();
        jTextFieldDAO = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jFindRemoveMethods = new javax.swing.JCheckBox();
        jPropertiesFile = new javax.swing.JCheckBox();
        jConnectionPoolClass = new javax.swing.JCheckBox();
        jJSFClass = new javax.swing.JCheckBox();
        jInterface = new javax.swing.JCheckBox();
        jJAXBAnnotations = new javax.swing.JCheckBox();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);
        getContentPane().setLayout(null);

        generateBtn.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N
        generateBtn.setLabel("Generate");
        generateBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generateBtnActionPerformed(evt);
            }
        });
        getContentPane().add(generateBtn);
        generateBtn.setBounds(490, 420, 370, 56);
        generateBtn.getAccessibleContext().setAccessibleName("generateBtn");

        dbList.setFont(new java.awt.Font("Ubuntu", 0, 16)); // NOI18N
        dbList.setForeground(new java.awt.Color(153, 153, 153));
        dbList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        dbList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                dbListMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(dbList);
        dbList.getAccessibleContext().setAccessibleName("");

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(10, 32, 157, 252);

        dbTablesList.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
        dbTablesList.setForeground(new java.awt.Color(102, 102, 102));
        dbTablesList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        dbTablesList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                dbTablesListMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(dbTablesList);

        getContentPane().add(jScrollPane2);
        jScrollPane2.setBounds(185, 32, 160, 252);

        dbColumnsList.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
        dbColumnsList.setForeground(new java.awt.Color(102, 102, 102));
        dbColumnsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        dbColumnsList.setEnabled(false);
        jScrollPane3.setViewportView(dbColumnsList);

        getContentPane().add(jScrollPane3);
        jScrollPane3.setBounds(690, 30, 170, 252);

        jLabel1.setText("Schemas:");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(10, 11, 70, 14);

        jLabel2.setText("Tables:");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(185, 11, 60, 14);

        jLabel3.setText("Columns:");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(690, 10, 70, 14);

        jButton1.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N
        jButton1.setLabel("Load schemas");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(10, 420, 335, 56);

        dbGenList.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
        dbGenList.setForeground(new java.awt.Color(102, 102, 102));
        dbGenList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        dbGenList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                dbGenListMouseClicked(evt);
            }
        });
        dbGenList.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dbGenListPropertyChange(evt);
            }
        });
        jScrollPane4.setViewportView(dbGenList);

        getContentPane().add(jScrollPane4);
        jScrollPane4.setBounds(490, 30, 180, 252);

        jButton2.setText("->");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(380, 90, 88, 23);

        jButton3.setText("All ->");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3);
        jButton3.setBounds(380, 130, 88, 23);

        jButton4.setText("<-");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton4);
        jButton4.setBounds(380, 170, 88, 23);

        jButton5.setText("<- All");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton5);
        jButton5.setBounds(380, 210, 89, 23);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("DTO package:");
        jLabel4.setToolTipText("");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(10, 300, 88, 17);

        jTextFieldDTO.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N
        jTextFieldDTO.setText("com.etfbl.net.dto");
        jTextFieldDTO.setPreferredSize(new java.awt.Dimension(122, 25));
        getContentPane().add(jTextFieldDTO);
        jTextFieldDTO.setBounds(10, 320, 335, 25);

        jTextFieldDAO.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N
        jTextFieldDAO.setText("com.etfbl.net.dao");
        getContentPane().add(jTextFieldDAO);
        jTextFieldDAO.setBounds(10, 380, 335, 25);

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("DAO package:");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(10, 360, 134, 17);

        jFindRemoveMethods.setSelected(true);
        jFindRemoveMethods.setText("Generate find and remove methods.");
        getContentPane().add(jFindRemoveMethods);
        jFindRemoveMethods.setBounds(490, 300, 220, 23);

        jPropertiesFile.setSelected(true);
        jPropertiesFile.setText("Generate properties file.");
        getContentPane().add(jPropertiesFile);
        jPropertiesFile.setBounds(490, 330, 210, 23);

        jConnectionPoolClass.setSelected(true);
        jConnectionPoolClass.setText("Generate connectionpool class.");
        getContentPane().add(jConnectionPoolClass);
        jConnectionPoolClass.setBounds(490, 360, 250, 23);

        jJSFClass.setText("Generate JSF2 (page, controller and class)");
        getContentPane().add(jJSFClass);
        jJSFClass.setBounds(490, 390, 310, 23);

        jInterface.setSelected(true);
        jInterface.setText("Generate Interfaces");
        getContentPane().add(jInterface);
        jInterface.setBounds(720, 300, 150, 23);

        jJAXBAnnotations.setText("JAXB annotations");
        getContentPane().add(jJAXBAnnotations);
        jJAXBAnnotations.setBounds(720, 330, 160, 23);

        jMenu1.setText("Main");

        jMenuItem2.setText("jMenuItem2");
        jMenu1.add(jMenuItem2);
        jMenu1.add(jSeparator1);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem1.setText("Exit");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");

        jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem3.setText("DB connection");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem3);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        setSize(new java.awt.Dimension(896, 547));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    protected void dbListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dbListMouseClicked
        //System.out.println("schemas: " + dbList.getSelectedValue());
        if(dbList.getSelectedValue() != null){
            dbColumnsList.setModel(new BaseListModel(new String[]{}));
            dbGenList.setModel(new BaseListModel(new String[]{}));
            dbTablesList.setModel(new BaseListModel(dbUtils.getAllTables(conn, dbList.getSelectedValue().toString())));
        }
    }//GEN-LAST:event_dbListMouseClicked

    protected void generateBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateBtnActionPerformed
        
        if (dbGenList.getModel() != null && dbGenList.getModel() instanceof BaseListModel) {
            String tables = null;
            
            //DTO class generator
            JavaBaseClassWriter dtoClassGen = new JavaBaseClassWriter();
            
            //DAOBase class generator
            JavaDAOClassWriter dao = new JavaDAOClassWriter();
            dao.setPackageName(jTextFieldDAO.getText());
            dao.setImportPackages(new String[]{
                "net.db.generator.utils.ClassGeneratorUtil",
                "java.io.InputStream",
                "java.io.Serializable",
                "java.lang.reflect.InvocationTargetException",
                "java.lang.reflect.Method",
                "java.lang.reflect.ParameterizedType",
                "java.math.BigDecimal",
                "java.sql.Connection",
                "java.sql.Date",
                "java.sql.PreparedStatement",
                "java.sql.ResultSet",
                "java.sql.SQLException",
                "java.sql.Time",
                "java.sql.Timestamp",
                "java.util.ArrayList",
                "java.util.Arrays",
                "java.util.List",
                "java.util.logging.Level",
                "net.etfbl.dao.base.IDAOBase",
                "java.util.logging.Logger",
                "net.db.generator.BasePK"
                //"net.etfbl.jgroky.jdbc.ConnectionPool"// use generate class
            });
            dao.generateClass();
            
            // write  ConnectionPool class
            if (jConnectionPoolClass.isSelected()) {
                JavaConnectionClassWriter jcon = new JavaConnectionClassWriter();
                jcon.setPackageName(jTextFieldDAO.getText());
                jcon.setImportPackages(new String[]{"java.sql.*", "java.util.*"});
                jcon.generateClass();
            }

            if (jPropertiesFile.isSelected()) {
                JavaConnectionPropertiesWriter jprop = new JavaConnectionPropertiesWriter();
                jprop.setClassName("ConnectionPool");
                jprop.setPackageName(jTextFieldDAO.getText());
                jprop.setProperties(getConnectionProperties());
                jprop.generateFile();
            }
            
            // generate class
            JavaDAOBaseClassWriter daogen = new JavaDAOBaseClassWriter();
            if(jFindRemoveMethods.isSelected())
            {
                daogen = new JavaDAOFullClassWriter();
            }
            daogen.setPackageName(jTextFieldDAO.getText());
            
            //generate DAO intefrace
//            JavaDAOBaseInterfaceWriter daointgen = new JavaDAOBaseInterfaceWriter();
//            daointgen.setPackageName(jTextFieldDAO.getText());
//            daointgen.setImportPackages(new String[]{
//                "net.etfbl.dao.base.IDAOBase"
//            });
            
            // generate base controller
            JSFBaseControllerClassWriter jc = new JSFBaseControllerClassWriter();
            jc.setPackageName("model.jsf");
            jc.setImportPackages(new String[]{
                "com.etfbl.net.dao.DAOBase",
                "java.io.Serializable",
                "java.util.logging.Level",
                "java.util.logging.Logger",
                "javax.faces.convert.Converter",
                "javax.faces.model.DataModel",
                "javax.faces.model.ListDataModel",
                "javax.faces.model.SelectItem",
                "models.jsf.util.JsfUtil",
                "models.jsf.util.PaginationManager",
                "javax.faces.event.AjaxBehaviorEvent"
            });
            
            if(jJSFClass.isSelected())
            {
                jc.generateClass();
            }
            
            // for Bundle
            Properties properties = new Properties();
            
            int size = dbGenList.getModel().getSize();
            
            for (int i = 0; i < size; i++) {
                
                List<DataBaseColumnType> columns = new ArrayList<>();
                tables = dbGenList.getModel().getElementAt(i).toString();
                
                dtoClassGen = new JavaBaseClassWriter();
                dtoClassGen.setPackageName(jTextFieldDTO.getText());
                dtoClassGen.setClassName(tables);
                daogen.setClassName(tables); 
                daogen.setImportPackages(new String[]{jTextFieldDTO.getText() + "." + ClassGeneratorUtil.humanize(tables)});
//                daointgen.setClassName(tables);
                
                BaseListModel dbcolumns = new BaseListModel(dbUtils.getAllColumns(conn, dbList.getSelectedValue().toString(), tables));
                for (int j = 0; j < dbcolumns.getSize(); j++) {
                    columns.add(DataBaseColumnType.toModel(dbcolumns.getElementAt(j).toString()));
                }
                
                ArrayList<String> primayKeysList = dbUtils.getPrimaryKeys(conn, dbList.getSelectedValue().toString(), tables);
                 
                List<BaseFieldModel> models = new ArrayList<BaseFieldModel>();
                for (DataBaseColumnType dataBaseColumnType : columns) {
                    BaseFieldModel bf = new BaseFieldModel(dataBaseColumnType.getName(), SQLTypeMap.convert(dataBaseColumnType.getType()));
                    bf.setPrimaryKey( primayKeysList.contains( dataBaseColumnType.getName() ) );
                    models.add(bf);
                }
                
                // for primary model class
                List<BaseFieldModel> primaryModels = new ArrayList<BaseFieldModel>();
                for (BaseFieldModel primaryModel : models) {
                    if(primaryModel.isPrimaryKey()){
                        primaryModels.add(primaryModel);
                    }
                }
                
                if(primayKeysList.size() > 1){
                    JavaBasePKClassWriter primaryKey = new JavaBasePKClassWriter();
                    primaryKey.setPackageName(jTextFieldDTO.getText());
                    primaryKey.setClassName(tables);
                    primaryKey.setFields(primaryModels);
                    primaryKey.setImportPackages(new String[]{"net.db.generator.BasePK"});
                    
                    daogen.setImportPackages(new String[]{
                        jTextFieldDTO.getText() + "." + ClassGeneratorUtil.humanize(tables),
                        jTextFieldDTO.getText() + "." + ClassGeneratorUtil.humanize(primaryKey.getClassName())
                    });
                    
                    primaryKey.generateClass();
                }
                
                dtoClassGen.setFields(models.toArray(new BaseFieldModel[models.size()]));
                String [] primaryKeyName = dbUtils.getPrimaryKeyName(conn, dbList.getSelectedValue().toString(), tables);
                dtoClassGen.setUniqueField(primaryKeyName);
                
                // generate interface for dto classes
                if (jInterface.isSelected()) {
                    JavaBaseInterfaceWriter dtoInterface = new JavaBaseInterfaceWriter();
                    dtoInterface.setPackageName(jTextFieldDTO.getText() + ".intf");
                    dtoInterface.setImportPackages(new String[]{
                        "java.io.Serializable"
                    });
                    dtoInterface.setClassName(tables);
                    dtoInterface.setFields(models.toArray(new BaseFieldModel[models.size()]));
                    dtoInterface.generateClass();

                    dtoClassGen.addInterfaceName(dtoInterface.getClassName());
                    
                    dtoClassGen.setImportPackages( new String []{ dtoInterface.getPackageName() + "." + ClassGeneratorUtil.humanize( dtoInterface.getClassName() ) } );
                }
                
                if (jJAXBAnnotations.isSelected()) {
                    String [] imports = dtoClassGen.getImportPackages();
                    List<String> imp = new ArrayList<String>( Arrays.asList(imports) );
                    imp.add("javax.xml.bind.annotation.XmlAccessType");
                    imp.add("javax.xml.bind.annotation.XmlAccessorType");
                    imp.add("javax.xml.bind.annotation.XmlAttribute");
                    imp.add("javax.xml.bind.annotation.XmlRootElement");
                    dtoClassGen.setImportPackages( (String []) imp.toArray(new String[imp.size()]) );
                    dtoClassGen.setJaxb(true);
                }
                
                dtoClassGen.generateClass();
                
                daogen.setUniqueField(primaryKeyName);
                daogen.setFields(models.toArray(new BaseFieldModel[models.size()]));
                daogen.generateClass();
                
//                daointgen.setFields(models.toArray(new BaseFieldModel[models.size()]));
//                daointgen.generateClass();
                
                if (jJSFClass.isSelected()) {
                    CommonJSFPagesGenerator jsf = new CommonJSFPagesGenerator(tables, daogen.getFields());
                    jsf.generateJSFPages();
                    // store properties for each pages....
                    properties.putAll(jsf.getProperties());
                    
                    CommonJSFControllerGenerator jsfp = new CommonJSFControllerGenerator(tables);
                    jsfp.setUniqueField(primaryKeyName);
                    jsfp.generateJSFController();
                    
                    JSFUtilWriter juw = new JSFUtilWriter();
                    juw.setClassName("JsfUtil");
                    juw.setPackageName("models.jsf.util");
                    juw.setImportPackages(new String[]{
                        "java.util.List",
                        "javax.faces.application.FacesMessage",
                        "javax.faces.component.UIComponent",
                        "javax.faces.context.FacesContext",
                        "javax.faces.convert.Converter",
                        "javax.faces.model.SelectItem"
                    });
                    juw.generateClass();
                    
                    JSFPaginationClassWriter jpc = new JSFPaginationClassWriter();
                    jpc.setClassName("PaginationManager");
                    jpc.setPackageName("models.jsf.util");
                    jpc.setImportPackages(new String[]{
                        "javax.faces.model.DataModel"
                    });
                    jpc.generateClass();

                }
            }
            
            
            if (jJSFClass.isSelected()) {
//                    generateBundle(properties);
            }

            System.out.println("Generete complite !!!");
            
            JOptionPane.showMessageDialog(this, "Generating successfully completed.", "Class generator", JOptionPane.INFORMATION_MESSAGE);
            
        }
        
        jButton1ActionPerformed(evt);// fixed for crash buggggg
        
    }//GEN-LAST:event_generateBtnActionPerformed

    private void generateBundle(Properties properties) {
        GeneratePropertiesFile g = new GeneratePropertiesFile(properties, Locale.ENGLISH);
        g.generateFile();
    }
    
    protected void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // get connection for current session
        conn = getConnection();
        
        dbTablesList.setModel(new BaseListModel(new String[]{}));
        dbColumnsList.setModel(new BaseListModel(new String[]{}));
        dbGenList.setModel(new BaseListModel(new String[]{}));
        dbList.setModel(new BaseListModel(dbUtils.getAllSchemas(conn)));
    }//GEN-LAST:event_jButton1ActionPerformed

    protected void dbTablesListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dbTablesListMouseClicked
        if(dbTablesList.getSelectedValue() != null){
            dbColumnsList.setModel(new BaseListModel(dbUtils.getAllColumns(conn, dbList.getSelectedValue().toString(),
                    dbTablesList.getSelectedValue().toString())));
        }
    }//GEN-LAST:event_dbTablesListMouseClicked

    protected void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        synchronized (this) {
            if (dbTablesList.getSelectedValue() != null) {
                BaseListModel model = addFromListModel((BaseListModel) dbGenList.getModel(), dbTablesList.getSelectedValue().toString());
                dbGenList.setModel(model);
                model = removeFromListModel((BaseListModel) dbTablesList.getModel(), dbTablesList.getSelectedValue().toString());
                dbTablesList.setModel(model);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    protected void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        synchronized (this) {
            if (dbTablesList.getModel() != null && dbTablesList.getModel() instanceof BaseListModel) {
                BaseListModel curentModel = (BaseListModel) dbTablesList.getModel();
                for (int i = 0; i < curentModel.getSize(); i++) {
                    BaseListModel model = addFromListModel((BaseListModel) dbGenList.getModel(), curentModel.getElementAt(i).toString());
                    dbGenList.setModel(model);
                    model = removeFromListModel((BaseListModel) dbTablesList.getModel(), curentModel.getElementAt(i).toString());
                    dbTablesList.setModel(model);
                }

            }
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    protected void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        synchronized (this) {
            if (dbGenList.getSelectedValue() != null) {
                BaseListModel model = addFromListModel((BaseListModel) dbTablesList.getModel(), dbGenList.getSelectedValue().toString());
                dbTablesList.setModel(model);
                model = removeFromListModel((BaseListModel) dbGenList.getModel(), dbGenList.getSelectedValue().toString());
                dbGenList.setModel(model);
            }
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    protected void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        synchronized (this) {
            if (dbGenList.getModel() != null && dbGenList.getModel() instanceof BaseListModel) {
                BaseListModel curentModel = (BaseListModel) dbGenList.getModel();
                for (int i = 0; i < curentModel.getSize(); i++) {
                    BaseListModel model = addFromListModel((BaseListModel) dbTablesList.getModel(), curentModel.getElementAt(i).toString());
                    dbTablesList.setModel(model);
                    model = removeFromListModel((BaseListModel) dbGenList.getModel(), curentModel.getElementAt(i).toString());
                    dbGenList.setModel(model);
                }

            }
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    protected void dbGenListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dbGenListMouseClicked
        if(dbGenList.getSelectedValue() != null){
            dbColumnsList.setModel(new BaseListModel(dbUtils.getAllColumns(conn, dbList.getSelectedValue().toString(),
                    dbGenList.getSelectedValue().toString())));
        }
    }//GEN-LAST:event_dbGenListMouseClicked

    protected void dbGenListPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dbGenListPropertyChange
        generateBtn.setEnabled((dbGenList.getModel().getSize() > 0));
    }//GEN-LAST:event_dbGenListPropertyChange

    protected void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        this.dispose();
        System.exit(0);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private ConnectionDialog connDialog = null;
    protected void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        connDialog = new ConnectionDialog(this, rootPaneCheckingEnabled);
        connDialog.setVisible(rootPaneCheckingEnabled);
//        System.out.println(" " + connDialog.getCurrent());
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    protected BaseListModel addFromListModel(BaseListModel model, String item){
        
        List<String> columns = new ArrayList<>();
        for (int i = 0; i < model.getSize(); i++) {
            columns.add(model.getElementAt(i).toString()); 
        }
//        if(!columns.contains(item));
            columns.add(item);
        return new BaseListModel(columns.toArray(new String[columns.size()]));
        
    }
    
    protected BaseListModel removeFromListModel(BaseListModel model, String item){
        
        List<String> columns = new ArrayList<>();
        for (int i = 0; i < model.getSize(); i++) {
            if(!model.getElementAt(i).toString().equals(item))
                columns.add(model.getElementAt(i).toString()); 
        }
        return new BaseListModel(columns.toArray(new String[columns.size()]));
        
    }
    
    protected Connection getConnection() {
        try {
            DBConnection.setConnectionPoolProperties(getConnectionProperties());
            DBConnection cp = DBConnection.getConnectionPool();
            Connection conn = cp.checkOut();
            return conn;
        } catch (Exception ex) {
            Logger.getLogger(ClassGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
     protected void checkConnection(Connection conn) {
        try {
            DBConnection.getConnectionPool().checkIn(conn);         
        } catch (Exception ex) {
            Logger.getLogger(ClassGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    ////////////////////////////////////////////////////////////////////////////
    //  system sound
    ////////////////////////////////////////////////////////////////////////////
    public void createAndShowGUI() {
        //Check the SystemTray support
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        final PopupMenu popup = new PopupMenu();
        final TrayIcon trayIcon =
                new TrayIcon(createImage("images/img.png", "ClassGenerator icon"));
        final SystemTray tray = SystemTray.getSystemTray();

        // Create a popup menu components
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
        CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
        Menu displayMenu = new Menu("Display");
        MenuItem errorItem = new MenuItem("Error");
        MenuItem warningItem = new MenuItem("Warning");
        MenuItem infoItem = new MenuItem("Info");
        MenuItem noneItem = new MenuItem("None");
        MenuItem exitItem = new MenuItem("Exit");

        //Add components to popup menu
        popup.add(aboutItem);
        popup.addSeparator();
//        popup.add(cb1);
        popup.add(cb2);
        popup.addSeparator();
        popup.add(displayMenu);
        displayMenu.add(errorItem);
        displayMenu.add(warningItem);
        displayMenu.add(infoItem);
        displayMenu.add(noneItem);
        popup.add(exitItem);

        trayIcon.setPopupMenu(popup);
        trayIcon.setImageAutoSize(true);

        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    //frame.add(popup);
                    //popup.show(frame, e.getXOnScreen(), e.getYOnScreen());
                    getContentPane().add(popup);
                    popup.show(getContentPane(), e.getX()-3, e.getYOnScreen()+58);
                }
            }
        });

        try {
            //frame.setVisible(true);
            //frame.setResizable(false);
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
            return;
        }

        trayIcon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null,
                        "This dialog box is run from System Tray");
            }
        });

        aboutItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null,
                        "This dialog box is run from the About menu item");
            }
        });

//        cb1.addItemListener(new ItemListener() {
//            public void itemStateChanged(ItemEvent e) {
//                int cb1Id = e.getStateChange();
//                if (cb1Id == ItemEvent.SELECTED) {
//                    trayIcon.setImageAutoSize(true);
//                } else {
//                    trayIcon.setImageAutoSize(false);
//                }
//            }
//        });

        cb2.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                int cb2Id = e.getStateChange();
                if (cb2Id == ItemEvent.SELECTED) {
                    trayIcon.setToolTip("Class generator");
                } else {
                    trayIcon.setToolTip(null);
                }
            }
        });

        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MenuItem item = (MenuItem) e.getSource();
                //TrayIcon.MessageType type = null;
                System.out.println(item.getLabel());
                if ("Error".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.ERROR;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is an error message", TrayIcon.MessageType.ERROR);

                } else if ("Warning".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.WARNING;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is a warning message", TrayIcon.MessageType.WARNING);

                } else if ("Info".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.INFO;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is an info message", TrayIcon.MessageType.INFO);

                } else if ("None".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.NONE;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is an ordinary message", TrayIcon.MessageType.NONE);
                }
            }
        };

        errorItem.addActionListener(listener);
        warningItem.addActionListener(listener);
        infoItem.addActionListener(listener);
        noneItem.addActionListener(listener);

        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tray.remove(trayIcon);
                System.exit(0);
            }
        });
    }

    //Obtain the image URL
    public static Image createImage(String path, String description) {
        URL imageURL = ClassGenerator.class.getResource(path);

        if (imageURL == null) {
            System.err.println("Resource not found: " + path);
            return null;
        } else {
            return (new ImageIcon(imageURL, description)).getImage();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClassGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClassGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClassGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClassGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClassGenerator().setVisible(true);
            }
        });
    }
    
    protected JFrame frame = new JFrame();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    protected javax.swing.JList dbColumnsList;
    protected javax.swing.JList dbGenList;
    protected javax.swing.JList dbList;
    protected javax.swing.JList dbTablesList;
    protected javax.swing.JButton generateBtn;
    protected javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    protected javax.swing.JCheckBox jConnectionPoolClass;
    protected javax.swing.JCheckBox jFindRemoveMethods;
    protected javax.swing.JCheckBox jInterface;
    protected javax.swing.JCheckBox jJAXBAnnotations;
    private javax.swing.JCheckBox jJSFClass;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    protected javax.swing.JCheckBox jPropertiesFile;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    protected javax.swing.JTextField jTextFieldDAO;
    protected javax.swing.JTextField jTextFieldDTO;
    // End of variables declaration//GEN-END:variables

    private SQLConnectionDatabase db;
    private DatabaseUtils dbUtils;
    private Connection conn;
    
    private void checkDataBaseConnection() {
        try {
            List<DataBaseConnectionModel> dmmodel = db.readFromDataBase();
            for (DataBaseConnectionModel dataBaseConnectionModel : dmmodel) {
                if(dataBaseConnectionModel.dbType.equals("MySql") && dataBaseConnectionModel.active == 1){
                    jButton1.setEnabled(true);
                }else{
                    jButton1.setEnabled(false);
                }
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(ClassGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private java.util.Properties getConnectionProperties(){
        java.util.Properties p = new java.util.Properties();
         try {
            List<DataBaseConnectionModel> dmmodel = db.readFromDataBase();
            for (DataBaseConnectionModel dataBaseConnectionModel : dmmodel) {
                if(dataBaseConnectionModel.dbType.equals("MySql") && dataBaseConnectionModel.active == 1){
                    p.put("databaseProducName", dataBaseConnectionModel.dbName);
                    p.put("username", dataBaseConnectionModel.dbUser);
                    p.put("password", dataBaseConnectionModel.dbPassword);
                    p.put("driver", dataBaseConnectionModel.dbDriver);
                    p.put("jdbcURL", dataBaseConnectionModel.jdbcURL + "?autoReconnect=true");
                    p.put("preconnectCount", "5");
                    p.put("maxIdleConnections", "25");
                    p.put("maxConnections", "25");
                    break;
                }else if(dataBaseConnectionModel.dbType.equals("Oracle") && dataBaseConnectionModel.active == 1){
                    p.put("databaseProducName", dataBaseConnectionModel.dbName);
                    p.put("username", dataBaseConnectionModel.dbUser);
                    p.put("password", dataBaseConnectionModel.dbPassword);
                    p.put("driver", dataBaseConnectionModel.dbDriver);
                    p.put("jdbcURL", dataBaseConnectionModel.jdbcURL);
                    p.put("preconnectCount", "5");
                    p.put("maxIdleConnections", "25");
                    p.put("maxConnections", "25");
                    break;
                }
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(ClassGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
       
        return p;
    }
}
